﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing; 
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using Tools = Microsoft.Office.Tools;
using CloudOfficeEngine;
using GoogleConnector;
using Utilities;
using UILibrary;

using Microsoft.Win32;

using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Collections;

//using OfficeInCloudWord2007.Proxy;

namespace OfficeInCloudWord2007
{
    public partial class ThisAddIn
    {
        private COE m_Engine;
        private WordLocalView m_LocalView;
        private Connector m_RemoteConnector;
        
        private bool DisabledMode = true;
        private TraceWrapper m_traceWrapper;
        private DbOperations m_dbOperations;
        private SnapshotManager m_snapshot;
        private Tools.CustomTaskPane m_MyGDocsPane = null;
        public Update m_updateChecker;

        private void CommunicationSetup()
        {
            m_LocalView = new WordLocalView(this.Application, m_dbOperations);
            m_RemoteConnector = new Connector();
            m_Engine = new COE(m_LocalView, m_RemoteConnector);
        }

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            CommonOperations.initPaths("\\Uprise Apps\\Word2007Log.txt", 
                                        "\\Uprise Apps\\Info.mdb",
                                        System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

            m_traceWrapper = new TraceWrapper();
            m_traceWrapper.initTraceListener();
            m_traceWrapper.traceSystemInfo(this.Application.Version,
                                    System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString());

            m_updateChecker = new Update();
            m_updateChecker.checkForUpdates(Properties.Resources.AppUpdateName,
                                            System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());

            m_dbOperations = new DbOperations(new DbManager(Utilities.Path.dbPath));

            m_snapshot = new SnapshotManager();

            //First Run
            RegistryKey kHKCU = Registry.CurrentUser;
            RegistryKey kFirstRun;
            try
            {
                kFirstRun = kHKCU.OpenSubKey("Software\\UpriseApps\\OfficeInCloudExcel2007", true);
                if (kFirstRun == null)
                {
                    kFirstRun = kHKCU.CreateSubKey("Software\\UpriseApps\\OfficeInCloudExcel2007", RegistryKeyPermissionCheck.ReadWriteSubTree);
                    kFirstRun.SetValue("FirstRun", 1); 
                    //MessageBox.Show("Office In Cloud for Google Docs (Excel 2007) was not properly installed. \n Please contact Uprise Apps support.", "Office In Cloud Error Message");
                }

                if (kFirstRun.GetValue("FirstRun").ToString().Equals("1"))
                {
                    //Registration Wizard
                    Registration regForm = new Registration(m_dbOperations);
                    if (DialogResult.OK == regForm.ShowDialog())
                    {
                        DisabledMode = false;
                    }
                }
                else DisabledMode = false;
            }
            catch(Exception ex)
            {
                Utilities.TraceWrapper.LogException("ThisAddIn_Startup error: " + ex.Message, ex);

                MessageBox.Show("Office In Cloud for Google Docs (Excel 2007) was not properly installed. \n Please contact Uprise Apps support.", "Office In Cloud Error Message");
            }

            CommunicationSetup();

            this.Application.DocumentBeforeClose += new Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(Application_DocumentBeforeClose); 
            this.Application.WindowActivate += new Word.ApplicationEvents4_WindowActivateEventHandler(Application_WindowActivate);
            this.Application.DocumentOpen += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentOpenEventHandler(Application_DocumentOpen);
        }

        void Application_DocumentOpen(Microsoft.Office.Interop.Word.Document Doc)
        {
            Tools.CustomTaskPane pane = null;

            if ((pane = getTaskPane(Doc.ActiveWindow, Properties.Resources.PaneTitle)) != null)
                pane.Visible = true;
        }

        private void Application_DocumentBeforeClose(Word.Document Doc, ref bool Cancel)
        {
            Tools.CustomTaskPane pane = null;

            if ((pane = getTaskPane(Doc.ActiveWindow, Properties.Resources.PaneTitle)) != null)
                this.CustomTaskPanes.Remove(pane);
        }

        private void Application_WindowActivate(Word.Document Doc, Word.Window Wn)
        {
            string title = Properties.Resources.PaneTitle;

            if (getTaskPane(Wn, title) == null)
                addTaskPane(Wn, title);
        }

        public void makePaneVisible(Word.Window Wn)
        {
            Tools.CustomTaskPane pane = null;
            string title = Properties.Resources.PaneTitle;

            if ((pane = getTaskPane(Wn, title)) != null)
                pane.Visible = true;
        }

        private void validateTaskPanes(Word.Window Wn)
        {
            ArrayList ct = new ArrayList();
            foreach (Tools.CustomTaskPane pane in this.CustomTaskPanes)
            {
                try
                {
                    //this expression generates the error for broken panels
                    bool sign = (pane.Window == Wn);
                }
                catch (Exception ex)
                {
                    ct.Add(pane);
                }
            }

            //remove all broken panels
            foreach (Tools.CustomTaskPane pane in ct)
                this.CustomTaskPanes.Remove(pane);
        }

        private Tools.CustomTaskPane getTaskPane(Word.Window Wn, string title)
        {
            //sometimes the customTaskPanes becomes broken, so we validate it
            validateTaskPanes(Wn);
       
            foreach (Tools.CustomTaskPane pane in this.CustomTaskPanes)
            {
                try
                {
                    if ((pane.Window == Wn) && (pane.Title == title))
                        return pane;
                }
                catch (Exception ex)
                {
                    Utilities.TraceWrapper.LogException("getTaskPane error: " + ex.Message, ex);
                }
            }

        return null;
        }

        public void addTaskPane(Word.Window parent, string title)
        {
            //this.Application.ShowWindowsInTaskbar = true;
            UserControl m_MyGDocsForm = new MyGDocsForm(
                                this.m_LocalView, 
                                this.DisabledMode, 
                                this.m_dbOperations,
                                this.m_traceWrapper,
                                this.m_snapshot,
                                Google.Documents.Document.DocumentType.Document);

            m_MyGDocsPane = this.CustomTaskPanes.Add(m_MyGDocsForm, title, parent);
            
            m_MyGDocsPane.DockPosition = Office.MsoCTPDockPosition.msoCTPDockPositionRight;
            m_MyGDocsPane.DockPositionRestrict =
                Office.MsoCTPDockPositionRestrict.msoCTPDockPositionRestrictNoHorizontal;
            m_MyGDocsPane.Width = 350;
            m_MyGDocsPane.Visible = true;

            m_MyGDocsPane.VisibleChanged += new EventHandler(m_MyGDocsPane_VisibleChanged);
            m_MyGDocsPane.DockPositionChanged += new EventHandler(m_MyGDocsPane_DockPositionChanged);

            System.Drawing.Size paneSize = new System.Drawing.Size(m_MyGDocsPane.Width, m_MyGDocsPane.Height);
            m_MyGDocsForm.Size = paneSize;
            m_MyGDocsPane.Visible = true;
            //((MyGDocsForm)m_MyGDocsForm).DoSilentLogin();
            m_snapshot.applySnapshot("clearLogin", m_MyGDocsForm);
        }

        public void m_MyGDocsPane_DockPositionChanged(object sender, EventArgs e)
        {
            Microsoft.Office.Tools.CustomTaskPane taskPane = sender as Microsoft.Office.Tools.CustomTaskPane;

            if (taskPane != null)
            {
                if (taskPane.DockPosition ==
                    Office.MsoCTPDockPosition.msoCTPDockPositionFloating)
                {
                    taskPane.Height = 500;
                    taskPane.Width = 500;
                }
                System.Drawing.Size paneSize = new System.Drawing.Size(taskPane.Width, taskPane.Height);
                taskPane.Control.Size = paneSize;
            }
        }


        public void m_MyGDocsPane_VisibleChanged(object sender, EventArgs e)
        {
            Microsoft.Office.Tools.CustomTaskPane taskPane =
                sender as Microsoft.Office.Tools.CustomTaskPane;

            if (taskPane != null)
            {
                if (taskPane.Visible)
                {
                    //taskPane.DockPosition = Office.MsoCTPDockPosition.msoCTPDockPositionRight;
                    Office.MsoCTPDockPosition mt = taskPane.DockPosition;
                }
            }
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            Trace.WriteLine("");
            Trace.WriteLine("");
            Trace.WriteLine("");
            m_traceWrapper.shutdownTraceListener();
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}
